More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Estimating π with François Viète’s Infinite Product

Long before computers existed, mathematicians were already trying to pin down the value of π using clever geometric constructions and infinite processes. One of the earliest breakthroughs came from a French mathematician named François Viète (1540–1603), who discovered one of the first known infinite product formulas in mathematics.

Viète’s work is especially remarkable because it predates calculus. Instead of using series or integrals, he built π using an infinite sequence of nested square roots derived from geometry.

The Viète Formula for π

Viète discovered that π can be expressed as an infinite product:
\frac{2}{\pi} = \frac{\sqrt{2}}{2} \cdot \frac{\sqrt{2 + \sqrt{2}}}{2} \cdot \frac{\sqrt{2 + \sqrt{2 + \sqrt{2}}}}{2} \cdot \cdots

Rearranging this formula gives:
\pi = \frac{2}{\displaystyle \prod_{n=1}^{\infty} a_n}

Where each term is built recursively:

  • a_1 = \frac{\sqrt{2}}{2}
  • a_2 = \frac{\sqrt{2+\sqrt{2}}}{2}
  • a_3 = \frac{\sqrt{2+\sqrt{2+\sqrt{2}}}}{2}

And so on…

  • a_n = \frac{\sqrt{2+\sqrt{2+\sqrt{2+\cdots}}}}{2}

As the number of terms (n) increases, the product converges slowly but steadily towards π. François Viète’s infinite product for estimating π can be visualised by drawing regular polygons inside a circle, where increasing the number of sides makes the polygon more closely approximate the circle and leads to a more accurate estimate of π.

Python Challenge

Your task is to write a Python program that estimates the value of π using Viète’s infinite product. However instead of computing infinite terms, you will approximate the value of π using a fixed number of iterations.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Recycling Bin Helper Program

Recycling correctly helps reduce waste and protects the environment. Different types of waste need to be placed in different bins, but remembering which item goes in which bin can sometimes be confusing.

In this Python challenge, you will create a simple recycling assistant that asks the user questions about an item they want to throw away and then tells them which bin it belongs in.

This challenge is ideal for beginners who want to practise:

  • Using variables
  • Getting user input
  • Using conditional statements (if, elif, else)
  • Making decisions in a program
  • Creating user-friendly text-based applications

The Recycling Bins

Our program will based on the following recycling scheme where each household has access to 5 bins of different colours:

Bin Waste Type
Blue Bin Plastics, plastic films, glass bottles, drink cartons (Tetra Pak) and cans.
Green Bin Paper, cardboard, books and cardboard packaging.
Grey Bin Food waste, plate scrapings, mouldy food, pet food, tea bags and coffee grounds.
Brown Bin Garden waste including grass clippings, leaves, dead flowers/plants and windfall fruit.
Black Bin General rubbish such as crisp packets, used nappies and polystyrene.

Python Challenge

To solve this challenge, we will write a Python program that ask the user about the item they are about to throw away. If it’s a recognised item, our program will try to decide straight away in which bin the item should go to.

For instance, we know that newspapers, magazines, books, leaflets and postcards should all end up in the green bin. so we can use some Python code to identify if the the item being thrown away belong to this list of items:

item = input("What are you recycling today?").lower()
if item in ["newspaper","magazine","book","leaflet","postcard"]:
   print("This " + item + " goes in the green bin.")

If this item is not in this list we can check if it belongs to other lists of recognisable items for the different recycling bins. To do so we will use elif statements:

item = input("What are you recycling today?").lower()
if item in ["newspaper","magazine","book","leaflet","postcard"]:
   print("This " + item + " goes in the green bin.")
elif item in ["plastic bottle","drink carton","tetra pak","metallic can","aluminium can","glass bottle"]:
   print("This " + item + " goes in the blue bin.")
elif ...
   ...

Your Turn…

Use the online Python IDE that you will find at the bottom of this blog post to complete the code and cater for a list of items for each of the 5 recycling bins of our recycling scheme.

Unrecognised items…

Now that you have completed the code to cater for all 5 bins, you can test it and see if gives you the right advise for different items.
You will quickly realise that using this approach it is not very practical to list every single possible item and that the program may not recognise the items the user want to throw, especially if this item is either not mentioned in the given list or is described differently.

So in this case we will get our program to ask the user a series of questions to determine what type of item they are disposing of.

For example the program could ask the following questions and use the following decision tree:

Python Code

Complete the following code online:

Extension Challenge 1

Some items should not end up in our bins but instead should be brought to the nearest recycling centre. These includes batteries, chemicals, and all forms of eWaste. Could you tweak your code to inform the user to not throw these items in any of their bins but instead bring them to their local recycling centre.


Extension Challenge 2

The above challenge is based on using selection in our code (If statements).

Your extra challenge is to use iteration (using a loop) within your code. You will tweak your code to allow the user to recycle multiple items by repeating the program until they choose to quit.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Python Challenge: Nicomachus’ Theorem

Nicomachus of Gerasa was an ancient Greek mathematician who lived around 60–120 AD. He is best known for his work Introduction to Arithmetic, one of the earliest surviving books on number theory.

One of the most famous results attributed to Nicomachus is a striking theorem about numbers and patterns. It shows that if you add together the cubes of the first n natural numbers, the result is exactly the same as squaring the sum of those numbers—a surprisingly elegant mathematical relationship.

In this challenge, we will write a Python program to verify Nicomachus’ theorem with any given value for n.

To do so we will first investigating one a surprising relationship between the sum of consecutive odd numbers and perfect square numbers. Effectively Nicomachus observed that:

The sum of the first n odd numbers is equal to n².

We can translate this observation into a mathematical equation:

1 + 3 + 5 + \cdots + (2n - 1) = n^2

For instance:
1 = 1^2 1 + 3 = 4 = 2^2 1 + 3 + 5 = 9 = 3^2 1 + 3 + 5 + 7 = 16 = 4^2

Now let’s use some Python code to verify this theory:

Nicomachus’s Theorem

Nicomachus’s Theorem can be defined as follows:

The sum of all the cubes of the first n natural numbers is equal to the square of the sum of those numbers.

We can translate this theorem into a mathematical equation:
1^3 + 2^3 + 3^3 + \cdots + n^3 = (1 + 2 + 3 + \cdots + n)^2

Using sigma notation, the same theorem can be expressed more compactly as:
\sum_{k=1}^{n} k^3 = \left( \sum_{k=1}^{n} k \right)^2

For instance:
1^3 = 1 = 1^2 1^3 + 2^3 = 9 = (1+2)^2 1^3 + 2^3 + 3^3 = 36 = (1 + 2 + 3)^2 1^3 + 2^3 + 3^3 +4^3 = 100 = (1 + 2 + 3 + 4)^2

Python Challenge

Your task is to reuse a similar approach as used in the above Python code to verify this theorem for any given value of n.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Graffiti Wall using CSS


The aim of this challenge is to create an eye-catching digital graffiti wall using HTML and CSS. By doing so we will improve our CSS skills focusing on CSS positioning, images and text formatting.

Learning Outcomes

In this tutorial, you will learn how to:

  • Position elements using absolute positioning
  • Resize images using CSS
  • Rotate images and text
  • Apply transparency effects
  • Import and use custom Google Fonts
  • Add text shadows and styling effects

Starter Code

We have started the graffiti wall using some HTML and CSS code. You will be able to edit this wall by clicking on the “Edit on Codepen” button.

The HTML code already contains all the images and text elements that will be placed on the wall.

<img src="https://www.101computing.net/wp/wp-content/uploads/arrow.png" id="arrow">
<img src="https://www.101computing.net/wp/wp-content/uploads/peace.png" id="peace">
<img src="https://www.101computing.net/wp/wp-content/uploads/tape.png" id="tape">
<img src="https://www.101computing.net/wp/wp-content/uploads/lightning-strike.png" id="lightning">
<img src="https://www.101computing.net/wp/wp-content/uploads/spraycan.png" id="spraycan">
<img src="https://www.101computing.net/wp/wp-content/uploads/dj-artist.png" id="dj-artist">
<img src="https://www.101computing.net/wp/wp-content/uploads/skateboarder.png" id="skateboarder">
<img src="https://www.101computing.net/wp/wp-content/uploads/astronaut.png" id="astronaut">

<div id="street-artist">#Street Artist</div>

Step 1: Creating the Brick Wall

We have started our CSS code to give our page a brick wall background using the following CSS code:

BODY {
  background-image: url(https://www.101computing.net/wp/wp-content/uploads/brick-wall.jpg);
  background-repeat: repeat;
} 

What does this do?

CSS Property Purpose
background-image Sets the image used as the page background
background-repeat Repeats the image to cover the page

Step 2: Positioning & Resizing Objects

We have started to position a couple elements including the peace symbol. To do so we are using absolute positioning in CSS which let us specify the exact position of our element on the page using the top and and left properties in CSS.

To resize our pictures, without stretching them, we will just specify either the width or the height of the picture in CSS. We do not include both the width and height properties as if we used both, we could end up stretching the picture. By only specifying either the width or the height, the other property will automatically adjust to keep the correct aspect ratio of the picture.

Here is the code to position and resize the peace sign on our wall:

#peace {
  position: absolute;
  top:120px;
  left:600px;
  width: 160px;
}

Your turn
Use different selectors such as #arrow, #dj-artist, #astronaut and use the relevant CSS properties to reposition and resize all the images to cover your graffiti wall.


Step 3: Rotating Objects

Now that your images are in position you can also rotate them using the following CSS code:

transform: rotate(20deg);

With his code you can use a positive or a negative angle to rotate your object clockwise or anti-clockwise.


Step 4: Flipping Images

To flip an image horizontally use the following CSS code:

transform: scaleX(-1);

Step 5: Layering Images

To change the layering order of your images when they overlap, you can use the z-index property in CSS:

z-index: 2;

Step 6: Importing Google Fonts & Formatting Text

For more exciting fonts that the standard web-safe fonts (Arial, Verdana, Times New Roman, etc.), we recommend importing your selection of Google fonts.

For instance, in the example provided, our text “StreetArtist” is formatted using the Frijole font from Google Fonts.

To import it and be able to use it within your CSS code, add the following line at the top of your CSS code:

@import url('https://fonts.googleapis.com/css2?family=Frijole&display=swap');

You can then use some CSS code to change the font family, size and colour of your text:

#urban {
  font-family:"Frijole";
  font-size:40pt;
  color:#441111;
}

Step 7: Adding a Shadow to the Text

It is possible t create a shadow effect to your text which can help improve the contrast and make your text easier to read especially when a page has a background picture.

text-shadow: 2px 2px #ffffff;

CSS Summary

Here is a summary of the CSS properties this challenged focused on:

Property Use
position:absolute Place elements anywhere on the page
top / left Specify the position/coordinates of an element on the page when using absolute positioning
z-index Change the layering orders of overlapping elements
transform Rotate or flip an element
opacity Apply transparency to an element
font-family Change the font of your text
font-size Change the size of your text
color Change the colour of your text
text-shadow Add outline/shadow effect to your text

UK Car Plate Number Decoder

Did you know you can find out where a UK car was first registered or how old it is just by looking at its number plate?

In this Python challenge, we will create a program that decodes a UK plate number. The program will ask the user to enter a UK car registration plate and the program will then:

  • Identify the regional registration area of the car
  • Calculate the approximate age of the vehicle

Decoding a UK Plate Number

Modern UK registration plates follow this format:

Regional Area Codes

The first letter of the area code tells us where the vehicle was registered sing the following letters/codes

Letter Region
A Anglia
B Birmingham
C Cymru (Wales)
D Deeside / Shrewsbury
E Essex
F Forest and Fens
G Garden of England
H Hampshire and Dorset
K Luton / Northampton
L London
M Manchester and Merseyside
N North
O Oxford
P Preston / Carlisle
R Reading
S Scotland
V Severn Valley
W West of England
Y Yorkshire

Age Identifier Rules

The two numbers in the registration plate indicate when the vehicle was first registered. It covers a 6-month period, which is why new plates are issued twice a year and the age identifier is determined based on the following rules:

  • For vehicles registered between March and August hold, we use the last 2 digits of the year it was put on the road. e.g for a car registered in March 2026, the age identifier code used is 26.
  • For cars registered from September to February, we use the same approach but add 50 to the code. So for a car registered in September 2026, the age identifier will be 26 + 50 = 76

So to determine the approximate age of a car based on the age identifier we will use the following rule:

Age of a Car?

Once we have established the year of registration of a car, we can estimate its age (in years) using the following formula:

What about the last 3 letters?

Unlike the first 4 characters of a plate which have a meaning, the final 3 letters don’t mean anything. Instead, these random 3-letter combinations are used to help keep each plate number unique compared to other plate numbers for cars registered at the same time.

Python Challenge

Let’s write a Python program that will:

    Ask the user to enter a valid UK registration plate number
    Validate this number ensuring that the plate number is exactly 8 characters long (including the space before the last 3 letters)
    Extract the first digit of the plate number (first digit of the area code)
    Extract the 2 number digits (age Identifier: the 3rd and 4th digits of the plate number)
    Lookup the area code within the list of area codes and output the area where the vehicle was registered.
    Calculate and output the estimated registration year of the vehicle.
    Calculate and output the estimated age (in years) of the vehicle.

We have started the code for you but this code is incomplete. Can you complete the code to calculate both the registration year and the estimated age of the car.

Testing:

Use you code to work out the area code and estimated age of the following vehicles:


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Build Your Own Pizza – Price Calculator

Welcome to this beginner-friendly Python challenge! In this task, you will create a simple pizza ordering system that calculates the total cost based on a customer’s choices. This is a great way to practise input handling, selection (if statements), and basic arithmetic in Python.

The Challenge

For this challenge, you will create a program that allows a customer to build their own pizza by choosing:

  • Pizza size (Small, Medium, Large)
  • Base type (Classic crust, thin crust or deep pan)
  • Number of toppings
  • Eat in or takeaway

Your program will then calculate and display the total price.

Finally, the user will be able to enter a discount code. If this discount code is correct they will receive a 20% discount on the price of their pizza!

To complete this challenge, you willl need to use:

  • input() statements to collect user choices
  • if / elif / else statements
  • Variables to store prices
  • Basic maths operations

Pizza Options & Costs

The following poster informs the customer of the process of making their own pizza and explains how the cost is calculated.

Python Code

We have started the code for you. Your job is to complete this code to let the user enter all their desired options for their pizza and to adjust the price of the pizza accordingly.

Extension Task: Discount Code

After entering all their options the customer should be given the opportunity to enter a discount code if they want to. If the user enter the code “P1ZZ4”, they should benefit from a 20% discount on the total price of their pizza!

Test Plan

Once your code is complete, test it using the following test plan to make sure all your calculations are correct!

Test # Input Values Expected Output Pass / Fail
#1 Pizza Size: Small (S)
Base: Deep
Number of Toppings 3
Eat in? Yes
Discount Code: N/A
Pizza Price: £14.50
#2 Pizza Size: Large (L)
Base: Thin
Number of Toppings 4
Eat in? No
Discount Code: FREEPIZZA
Pizza Price: £17.00
#3 Pizza Size: Medium (M)
Base: Classic
Number of Toppings 5
Eat in? Yes
Discount Code: P1ZZ4
Pizza Price: £14.00
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Estimating Pi Using Coprime Numbers

Did you know you can estimate the value of π (pi) using probability and number theory?

This challenge explores a surprising mathematical relationship:
The probability that two randomly chosen integers are coprime, P(\text{coprime}) is equal to \frac{6}{\pi^2}

Coprime numbers?

Two numbers are coprime if their only common factor is 1.

Using this idea, you can estimate π by randomly generating pairs of integers and checking how often they are coprime.

If:
P(\text{coprime}) = \frac{6}{\pi^2}
Then we can rearrange to estimate π:
\pi \approx \sqrt{\frac{6}{P(\text{coprime})}}

So the aim of this challenge will be to write a program to:

  • Generate many random pairs of integers
  • Count how many of these pairs are coprime
  • Use the ratio to estimate π

Not that to work out if two numbers are coprime, we will need to create a function to calculate their Greatest Common Denominator.

Step 1: Generating N pairs of random integers

For this step we will use the random library to generate random integer values (between 1 and 10,000), and a for loop, to generate N pairs.

import random, math

N = 1000
for i in range(0,N):
   number1 = random.randint(1,10000)
   number2 = random.randint(1,10000)

Step 2: Finding out if our pair of numbers are coprime

To check if two numbers are coprime, we first need to calculate their Greatest Common Denominator. We can do so using the following function, based on Euclid’s Division Algorithm:

def gcd(a, b):
    # Repeat until b becomes 0
    while b != 0:
        remainder = a % b   # Find the remainder when a is divided by b
        a = b               # Move b into a
        b = remainder       # Move remainder into b

    # When b is 0, a contains the GCD
    return a

We can use this function in our previous for loop to count how many pairs of numbers are coprime:

import random, math

N = 1000
coprime_count = 0

for i in range(0,N):
   number1 = random.randint(1,10000)
   number2 = random.randint(1,10000)
   if gcd(number1, number2) == 1:
      coprime_count = coprime_count + 1

Step 3: Outputting the ratio of coprime pairs:

We can now calculate and display the ratio of coprime pairs (Probability that two randomly generated numbers are coprime):

P(coprime) = \frac{coprime\_count}{N}
probability = coprime_count / N

Estimating Pi

We can now estimate Pi using the following formula:
\pi \approx \sqrt{\frac{6}{P(\text{coprime})}}

pi_estimate = math.sqrt(6 / probability)

And finally we can display our estimate on screen as well as calculate the percentage of accuracy of our estimate:

print("Number of pairs", N)
print("Number of coprime", coprime_count)
print("Estimated value of Pi:", pi_estimate)
print("Actual value of Pi:", math.pi)
print("Percentage of accuracy:", 100 - 100 * abs(math.pi - pi_estimate)/math.pi)

Python Code

Your turn! You can now complete the code below:

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Pygame Animations using a Spritesheet

In this tutorial, we will learn how to animate a character in Python using the Pygame library and a spritesheet. Instead of loading lots of separate images to animate our main sprite/character, we will use one single image containing multiple frames — a much more efficient and professional approach used in real games!

Our learning objectives are as follows:

  • Understand what a spritesheet is
  • Load and display images in Pygame
  • Extract frames from a spritesheet
  • Animate a walking character

What’s a Spritesheet?

A spritesheet is a single image that contains multiple frames to be used to create a frame-based animation.

For example: a walking character might have 6 frames showing different leg and arm positions.

Instead of loading 6 separate images, we:

  • Load one image (called a spritesheet)
  • “Cut” it into smaller pieces (frames)
  • Display these frames in sequence

Here is a spritesheet to create an animated walking ninja girl. Our animation will contain 9 frames:

When we animated these frames in sequence we will get the following animation:

Let’s now investigate the Python code to complete this animation with a 2D game implemented using the Pygame library.

Python Tutorial

Step 1: Setup the game (using Pygame)

You will need to make sure that the Pygame library is already installed on your computer.

The you will create your main python file and use the following code to initialise your game:

import pygame
import sys

pygame.init()

# Create game window
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Spritesheet Animation")

Step 2: Loading the Spritesheet

You will need to download the spritesheet below and save it in the same folder as where your Python file is saved.

Now add the following line of code to load the spritesheet file:

spritesheet = pygame.image.load("character_spritesheet.png").convert_alpha()

Step 3: Extracting Frames from the Spritesheet

We will use the following function to extract the different frames from the spritesheet: (Add this function at the top of your code)

def load_frames(sheet, x, y, frame_width, frame_height, num_frames):
    frames = []

    for i in range(num_frames):
        frame = sheet.subsurface(
            pygame.Rect(x + i * frame_width, y, frame_width, frame_height)
        )
        frames.append(frame)

    return frames

After loading the spritesheet, we will call our function. For instance to extract the top row of frames (running animation) we will start extraxcting 9 frames from position x=0 and y=0, each frame being 120 pixels wide and 160 pixels high.

Here the code we will use to extract these 9 frames:

frames = load_frames(spritesheet, 0, 0, 120, 160, 9)

We will also use two animation variables as follows:

current_frame = 0
animation_speed = 0.15

Step 4: Animating our character

Now let’s add some code to the main program loop of our game:

clock = pygame.time.Clock()
carryOn = True
while carryOn:
   screen.fill((30, 30, 30))

   # Handle events
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False

   # Update animation
   current_frame += animation_speed
   if current_frame >= len(frames):
      current_frame = 0

   # Draw current frame
   screen.blit(frames[int(current_frame)], (100, 300))

   pygame.display.flip()
   clock.tick(60)

pygame.quit()
sys.exit()

Your Turn

Use the above code and spritesheet to reproduce the animation of the ninja-girl running.

The tweak the code provided to make a jumping ninja girl animation.

Finally, create one more animation of the ninja girl attacking!

Using Object Oriented Programming

Within a Pygame project, it is very likely that you will define a separate class for the main character of your game. So let’s rework the code provided above to create a NinjaGirl class. We will then respond to keyboards input to change the state of our player (e.g. from idle to running or attacking). We will also use some code to flip our character so that we can have them looking/running right or left.

When trying the code provided below use the following keyboard inputs:

  • Right arrow to run towards the right
  • Left arrow to run towards the left
  • Space bar to attack
main.pyninja_girl.py

Python Code: Main.py file

# Ninja Girl Animation using Pygame - www.101computing.net/pygame-animations-using-a-spritesheet/

import pygame
import sys
from ninja_girl import NinjaGirl

IDLE = 0
RUN = 1
JUMP = 2
ATTACK = 3
DEAD = 4

pygame.init()

# Create game window
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Spritesheet Animation")

# Create sprite
player = NinjaGirl(100, 300)
all_sprites = pygame.sprite.Group(player)

clock = pygame.time.Clock()

running = True

while running:
   screen.fill((30, 30, 30))

   # Events
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False

   keys = pygame.key.get_pressed()

    # State logic
   if keys[pygame.K_RIGHT]:
       player.set_state(RUN)
       player.rect.x += 3
       player.facing_right = True

   elif keys[pygame.K_LEFT]:
       player.set_state(RUN)
       player.rect.x -= 3
       player.facing_right = False
   elif keys[pygame.K_SPACE]:
       player.set_state(ATTACK)
   else:
       player.set_state(IDLE)


   # Update + draw
   all_sprites.update()
   all_sprites.draw(screen)

   pygame.display.flip()
   clock.tick(60)

pygame.quit()
sys.exit()

Python Code: ninja_girl.py file

import pygame

IDLE = 0
RUN = 1
JUMP = 2
ATTACK = 3
DEAD = 4

class NinjaGirl(pygame.sprite.Sprite):
   #This class represents a ball. It derives from the "Sprite" class in Pygame.

   def __init__(self, x, y):
      super().__init__()

      # State
      self.state = IDLE
      self.facing_right = True

      # Animation
      self.animations = {}
      self.current_frame = 0
      self.animation_speed = 0.15

      # Load spritesheets
      self.load_animations()

      # Starting image
      self.image = self.animations[self.state][0]
      self.rect = self.image.get_rect()

      # Position
      self.rect.x = x
      self.rect.y = y


   def load_frames(self, filename, x, y, frame_width, frame_height, num_frames):
      sheet = pygame.image.load(filename).convert_alpha()
      frames = []

      for i in range(num_frames):
         frame = sheet.subsurface(
            pygame.Rect(x + i * frame_width, y, frame_width, frame_height)
         )
         frames.append(frame)

      return frames


   def load_animations(self):
      self.animations[IDLE] = self.load_frames("spritesheet-ninja-girl.png", 960, 350, 120, 160, 1)
      self.animations[RUN] = self.load_frames("spritesheet-ninja-girl.png", 0, 0, 120, 160, 9)
      self.animations[JUMP]  = self.load_frames("spritesheet-ninja-girl.png", 0, 160, 120, 160, 9)
      self.animations[ATTACK]  = self.load_frames("spritesheet-ninja-girl.png", 0, 350, 200, 160, 4)
      self.animations[DEAD] = self.load_frames("spritesheet-ninja-girl.png", 800, 350, 200, 160, 1)


   def update(self):
      frames = self.animations[self.state]

      self.current_frame += self.animation_speed
      if self.current_frame >= len(frames):
         self.current_frame = 0

      frame = frames[int(self.current_frame)]

      # Flip image if facing left
      if not self.facing_right:
         frame = pygame.transform.flip(frame, True, False)

      self.image = frame


   def set_state(self, new_state):
      if self.state != new_state:
         self.state = new_state
         self.current_frame = 0  # Reset animation



unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Tagged with:

Extracurricular Activity Selector

A high school teacher needs your help! They have been asked to organise a full set of registers for students to take part in some extracurricular activities organised by the school.

There are 100 students in the year group, and each student has selected three preferred activities. Your task is to write a Python program that:

  • Allocates each student to an activity
  • Prioritises their 1st choice, then 2nd, then 3rd
  • Ensures no activity exceeds its maximum capacity
  • Identifies any students who could not be allocated

Available Activities

There are 10 activities available:

  • Rounders
  • Football
  • Basketball
  • Dance
  • Athletics
  • Chess Club
  • Coding Club
  • Arts & Crafts
  • Tennis
  • Badminton

Each activity has a maximum capacity of 10 students.

The Data

Student choices are stored in a CSV file called choices.csv like this:

FirstName,LastName,Choice1,Choice2,Choice3,
James,Bond,Basketball,Athletics,Coding Club,
Lara,Croft,Football,Dance,Athletics,
...

The complete file is provided in the Python IDE provided below.

Python Challenge

Your task is to write a Python program that will :

    Reads the CSV file
    Loops through each student
    Allocates them:

      First choice if available
      Otherwise second choice
      Otherwise third choice

    Keeps track of:

      Students assigned to each activity
      Students who could not be assigned

Example Output

This is what the output of your code would look like:

=== Activity Allocations ===

Football (10 students)
- Lara Croft
- John Smith
...

Basketball (10 students)
- James Bond
...

=== Unallocated Students ===
- Alex Turner
- Sarah Connor

Hints

Check the following hints to help you plan your solution!

  • Use a dictionary to store activities and their current student lists
  • Use the csv module to read the file
  • Think carefully about how to check if an activity is full
  • You may want a separate list for unallocated students

Python Code

We have started the code to help you read and extract the data from the CSV file. Your task is now to complete this code to allocate each students to an activity based on their preferences when possible.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

The Goldbach Conjecture (Python Challenge)

The Goldbach Conjecture is an unproven mathematical rule, proposed by Christian Goldbach in 1742, stating that every even integer greater than 2 is the sum of two prime numbers. Despite verification by computers up to 4 x 1018, no formal proof exists, making it one of the oldest unsolved problems in number theory!

Every even number greater than 2 can be expressed as the sum of two prime numbers.

Let’s look at some examples:

  • 10 = 3 + 7
  • 28 = 5 + 23
  • 50 = 3 + 47

Our challenge is to write a Python program that tests this conjecture for any even number provided by the end-user of this program. Our program will need to:

    Ask the user to enter an even number greater than 2
    Find two prime numbers that add up to this number
    Display the result

Example Output

Enter an even number: 28
28 = 5 + 23

Prime Numbers?

A prime number is a whole number greater than 1 that cannot be exactly divided by any whole number other than itself and 1.

The first 20 prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, and 71.

To help test the Goldbach Conjecture, we will use a function isPrime() that takes a whole positive number as a parameter and returns whether or not this number is a prime number. Here is the code for this function:

def isPrime(n):
   if n < 2:
      return False
   for i in range(2, int(n**0.5) + 1):
      if n % i == 0:
         return False
   return True

You can test this function using the following code:

number = int(input("Enter a whole number"))
if isPrime(number):
   print("This number is a prime number!")
else:
   print("This number is a not a prime number!")

Testing the Goldbach Conjecture

We are now going to implement an algorithm to test the Goldbach Conjecture for any given number. We will base our Python code on the following flowchart:

Python Code

Use the following IDE to complete the code for testing the Goldbach conjecture based on the above flowchart:

Extension Task

Tweak your code to use an iterative approach to check all even numbers from 4 up to 1000 and display their prime pairs.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area